package net.suncaper.mvc.web.controller;

import net.suncaper.mvc.common.framework.simplemvc.RequestMapping;
import net.suncaper.mvc.common.utils.JSONUtil;
import net.suncaper.mvc.common.utils.Result;
import net.suncaper.mvc.model.domain.Room;
import net.suncaper.mvc.model.vo.RoomVO;
import net.suncaper.mvc.common.utils.EntityConverter;
import net.suncaper.mvc.service.IRoomService;
import net.suncaper.mvc.service.impl.RoomServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;

/**
 * 房间控制层
 */
@RequestMapping("/api/room")
public class RoomController {
    // 注入房间业务层接口
    private final IRoomService roomService = new RoomServiceImpl();

    /**
     * 添加房间信息
     * 请求参数：roomType（房型）、hotelName（酒店名称）、imageUrl（图片URL）、price（价格）、availableCount（可用数量）、breakfast（早餐类型）
     */
    @RequestMapping("/add.do")
    public void addRoom(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            // 获取请求参数
            String roomType = request.getParameter("roomType");
            String hotelName = request.getParameter("hotelName");
            String imageUrl = request.getParameter("imageUrl");
            BigDecimal price = new BigDecimal(request.getParameter("price"));
            Integer availableCount = Integer.parseInt(request.getParameter("availableCount"));
            String breakfast = request.getParameter("breakfast");

            // 构建房间对象
            Room room = new Room();
            room.setRoomType(roomType);
            room.setHotelName(hotelName);
            room.setImageUrl(imageUrl);
            room.setPrice(price);
            room.setAvailableCount(availableCount);
            room.setBreakfast(breakfast);

            // 调用业务层添加房间
            boolean isSuccess = roomService.addRoom(room);
            JSONUtil.printByJSON(response, Result.success(isSuccess));
        } catch (Exception e) {
            // 捕获业务异常并返回错误信息
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 根据酒店名称查询房间列表
     * 请求参数：hotelName（酒店名称）
     */
    @RequestMapping("/listByHotel.do")
    public void getRoomsByHotel(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            String hotelName = request.getParameter("hotelName");
            List<Room> rooms = roomService.getRoomsByHotel(hotelName);
            if (rooms != null && !rooms.isEmpty()) {
                java.util.List<RoomVO> roomVOList = EntityConverter.convertToRoomVOList(rooms);
                JSONUtil.printByJSON(response, Result.success(roomVOList));
            } else {
                JSONUtil.printByJSON(response, Result.error("未找到符合条件的房间"));
            }
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 根据房型和酒店名称查询单个房间
     * 请求参数：roomType（房型）、hotelName（酒店名称）
     */
    @RequestMapping("/get.do")
    public void getRoomByTypeAndHotel(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            String roomType = request.getParameter("roomType");
            String hotelName = request.getParameter("hotelName");
            Room room = roomService.getRoomByTypeAndHotel(roomType, hotelName);
            if (room != null) {
                RoomVO roomVO = EntityConverter.convertToRoomVO(room);
                JSONUtil.printByJSON(response, Result.success(roomVO));
            } else {
                JSONUtil.printByJSON(response, Result.error("房间不存在"));
            }
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 查询所有房间信息
     */
    @RequestMapping("/listAll.do")
    public void getAllRooms(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            List<Room> allRooms = roomService.getAllRooms();
            if (allRooms != null && !allRooms.isEmpty()) {
                java.util.List<RoomVO> roomVOList = EntityConverter.convertToRoomVOList(allRooms);
                JSONUtil.printByJSON(response, Result.success(roomVOList));
            } else {
                JSONUtil.printByJSON(response, Result.error("暂无房间信息"));
            }
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 更新房间信息
     * 请求参数：roomType（房型）、hotelName（酒店名称）、imageUrl（图片URL，可选）、price（价格，可选）、availableCount（可用数量，可选）、breakfast（早餐类型，可选）
     */
    @RequestMapping("/update.do")
    public void updateRoom(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            // 获取基础定位参数
            String roomType = request.getParameter("roomType");
            String hotelName = request.getParameter("hotelName");

            // 构建房间对象（仅更新传递的非空参数）
            Room room = new Room();
            room.setRoomType(roomType);
            room.setHotelName(hotelName);

            // 可选参数：图片URL
            String imageUrl = request.getParameter("imageUrl");
            if (imageUrl != null && !imageUrl.trim().isEmpty()) {
                room.setImageUrl(imageUrl);
            }

            // 可选参数：价格
            String priceStr = request.getParameter("price");
            if (priceStr != null && !priceStr.trim().isEmpty()) {
                room.setPrice(new BigDecimal(priceStr));
            }

            // 可选参数：可用数量
            String countStr = request.getParameter("availableCount");
            if (countStr != null && !countStr.trim().isEmpty()) {
                room.setAvailableCount(Integer.parseInt(countStr));
            }

            // 可选参数：早餐类型
            String breakfast = request.getParameter("breakfast");
            if (breakfast != null && !breakfast.trim().isEmpty()) {
                room.setBreakfast(breakfast);
            }

            // 调用业务层更新房间
            boolean isSuccess = roomService.updateRoom(room);
            JSONUtil.printByJSON(response, Result.success(isSuccess));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 删除房间
     * 请求参数：roomType（房型）、hotelName（酒店名称）
     */
    @RequestMapping("/delete.do")
    public void deleteRoom(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            String roomType = request.getParameter("roomType");
            String hotelName = request.getParameter("hotelName");
            boolean isSuccess = roomService.deleteRoom(roomType, hotelName);
            JSONUtil.printByJSON(response, Result.success(isSuccess));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 调整房间价格
     * 请求参数：roomType（房型）、hotelName（酒店名称）、newPrice（新价格）
     */
    @RequestMapping("/adjustPrice.do")
    public void adjustRoomPrice(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            String roomType = request.getParameter("roomType");
            String hotelName = request.getParameter("hotelName");
            BigDecimal newPrice = new BigDecimal(request.getParameter("newPrice"));
            boolean isSuccess = roomService.adjustRoomPrice(roomType, hotelName, newPrice);
            JSONUtil.printByJSON(response, Result.success(isSuccess));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 补充房间库存
     * 请求参数：roomType（房型）、hotelName（酒店名称）、addCount（补充数量）
     */
    @RequestMapping("/addStock.do")
    public void addRoomStock(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            String roomType = request.getParameter("roomType");
            String hotelName = request.getParameter("hotelName");
            int addCount = Integer.parseInt(request.getParameter("addCount"));
            boolean isSuccess = roomService.addRoomStock(roomType, hotelName, addCount);
            JSONUtil.printByJSON(response, Result.success(isSuccess));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }
}